<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8"/>
    <title>Custom Editor Example</title>
    <script src="https://cdn.jsdelivr.net/npm/@json-editor/json-editor@latest/dist/jsoneditor.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KK94CHFLLe+nY2dmCWGMq91rCGa5gtU4mk92HdvYe+M/SXH301p5ILy+dN9+nJOZ" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ENjdO4Dr2bkBIFxQpeoTz1HIcje39Wm4jDKdf19U8gI4ddQ3GYNS7NTKfAdVQSZe" crossorigin="anonymous"></script>
</head>
<body>

<div class="container">
    <h1>Custom Editor Example (switch)</h1>
    <p>Bootstrap 5 style switch editor</p>

    <div id='editor_holder'></div>
    <br>
    <br>
    <p>Value:</p>
    <pre id="value"></pre>
</div>

<script>
  /* --------------------------------------------- create custom editor class */

  class CustomEditor extends JSONEditor.AbstractEditor {
    build () {
      super.build()

      // control
      this.control = document.createElement('div')
      this.control.classList.add('form-check')
      this.control.classList.add('form-switch')

      // input
      this.input = document.createElement('input')
      this.input.setAttribute('type', 'checkbox')
      this.input.setAttribute('id', this.path + 'test')
      this.input.classList.add('form-check-input')

      // label
      this.label = document.createElement('label')
      this.label.setAttribute('for', this.path + 'test')
      this.label.classList.add('form-check-label')
      this.label.textContent = this.schema.title

      // appends
      this.container.appendChild(this.control)
      this.control.appendChild(this.input)
      this.control.appendChild(this.label)
    }

    postBuild () {
      super.postBuild()

      this.input.addEventListener('change', e => {
        e.preventDefault()
        e.stopPropagation()
        this.value = e.currentTarget.checked
        this.onChange(true)
      })
    }
  }

  /* ---------------------------------------------- add class to editors list */

  JSONEditor.defaults.editors.customEditor = CustomEditor

  /* ----------------------------------------------------------- add resolver */

  JSONEditor.defaults.resolvers.unshift(function (schema) {
    if (schema.type === 'boolean' && schema.format === 'custom') {
      return 'customEditor'
    }
  })

  /* ----------------------------------------------------- instanciate editor */

  var editor = new JSONEditor(document.getElementById('editor_holder'), {
    schema: {
      'type': 'boolean',
      'format': 'custom',
      'title': 'Custom'
    }
  })

  editor.on('change', function () {
    document.querySelector('#value').textContent = JSON.stringify(editor.getValue(), null, 2)
  })
</script>
</body>
</html>
